首页
首页

nginx 反向代理,负载均衡使用详解

系统:centos 7

安装:

1、rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

2、yum install nginx -y

###Nginx之反向代理

1、安装httpd

1
2
3
yum install -y httpd

echo 'hello world' >/var/www/html/index.html

2、配置nginx.conf

1
2
3
4
5
6
7
#cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/new.conf
#mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/bak
#vim /etc/nginx/conf.d/new.conf
location / {
proxy_pass http://192.168.159.139; # 反向代理到那条
proxy_set_header X-Real-IP $remote_addr; #加上这一行,是为了可以使源ip写入到日志中
}

3、 配置httpd使源ip保存到日志中

1
2
3
4
5
6
#vim /etc/httpd/conf/httpd.conf
将LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined 替换为
LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

将LogFormat "%h %l %u %t \"%r\" %>s %b" common 替换为
LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b" common

4、重启服务

1
2
systemctl restart httpd
systemctl restart nginx

###Nginx之负载均衡

负载均衡使用到的主要是:Nginx的HTTP Upstream模块

1、定义负载均衡的名字和设备

1
2
3
4
upstream webserver {
server 192.168.159.131:80 weight=1 max_fails=2 fail_timeout=2;
server 192.168.159.139:80 weight=1 max_fails=2 fail_timeout=2;
}

以上为定义了一个webserver组 包含俩台提供服务的主机

1
2
3
4
5
6
7
8
location / {
proxy_pass http://webserver;
proxy_set_header X-Real-IP $remote_addr; #加上这一行
}
location /html/ {
proxy_pass http://webserver1/html/;
proxy_set_header X-Real-IP $remote_addr; #加上这一行
}

以上为分别调用的使用方法

2、重启nginx

systemctl restart nginx

__常见错误_____

问题:centos下nginx bind() to 0.0.0.0:* failed

原因:seLinux限制了http的端口

解决方法:

1、关闭seLinux

    临时关闭:setenforce 0
    永久关闭:
        vim /etc/sysconfig/selinux 
        修改SELINUX=enforcing ----> SELINUX=disabled

2、添加端口到例外
1
2
3
yum -y install policycoreutils-python ####安装相关工具
semanage port -a -t http_port_t -p tcp 8090 #### 添加8090为例外
semanage port -l | grep http_port_t #### 检查例外

End

支持一下
扫一扫,我会更有动力更新
  • 微信扫一扫
  • 支付宝扫一扫